﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using FeiXunHelper.Definitions;
using FeiXunHelper.Services;
using TDLib.UIs.Forms;
using TDLib.Utils;
using System.Diagnostics;
using FeiXunHelper.Utils;
using FeiXunHelper.Definitions.Product;
using FeiXunHelper.Definitions.Address;
using FeiXunHelper.UIs.Common;
using FeiXunHelper.UIs.Login;
using FeiXunHelper.UIs.Query;

namespace FeiXunHelper.UIs
{
    public partial class FrmMain : FrmIconBase
    {
        private FeiXunService _service = new FeiXunService();
        private MusicPlayer _musicPlayer = null;
        private QQNotifier _qqNotify = new QQNotifier();
        private bool _isMonitorRunning = false;
        private Thread _monitorThread = null;
        private long _outputRows = 0;
        private Color _onSaleColor;

        public FrmMain()
        {
            InitializeComponent();
            InitUI();
            InitSkin();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            _musicPlayer = new MusicPlayer(this);
        }

        private void InitUI()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            // 初始化窗体尺寸
            this.Width = 1245;
            this.Height = 764;
            // 初始化托盘双击事件
            this.notifyIcon1.MouseDoubleClick +=(o,args)=>
                {
                    if (args.Button == System.Windows.Forms.MouseButtons.Left)
                    {
                        this.notifyIcon1.Visible = false;
                        this.Show();
                        this.WindowState = FormWindowState.Normal;
                    }
                };
            // 初始化色块
            _onSaleColor = this.colorBlock2.BackColor;
            this.colorBlock2.BackColorChanged += (o, args) => _onSaleColor = this.colorBlock2.BackColor;
            // 填充监控页面中的种类
            foreach (var category in ProductCategory.AllCategory)
            {
                int index = this.panelSeries.Controls.Count - 1;
                CheckBox checkBoxLast = this.panelSeries.Controls[index] as CheckBox;
                CheckBox checkBoxNew = new CheckBox();
                checkBoxNew.Anchor = AnchorStyles.Left | AnchorStyles.Top;
                checkBoxNew.Text = category.Name;
                checkBoxNew.AutoSize = true;
                checkBoxNew.Tag = category;
                checkBoxNew.Font = new Font("宋体", 9);
                checkBoxNew.Top = checkBoxLast.Top;
                checkBoxNew.Left = checkBoxLast.Right + 2;
                this.panelSeries.Controls.Add(checkBoxNew);
            }
            (this.panelSeries.Controls[0] as CheckBox).Checked=true;
            // 填充音乐列表
            string audioPath = Application.StartupPath + "\\audio";
            string[] files = System.IO.Directory.GetFiles(audioPath);
            foreach (var file in files)
            {
                string filename = System.IO.Path.GetFileName(file);
                this.comboBoxMusicList.Items.Add(filename);
            }
            if (this.comboBoxMusicList.Items.Count > 0)
            {
                this.comboBoxMusicList.SelectedIndex = 0;
            }
        }

        private void InitSkin()
        {
            string skinFile = ResUtil.GetResAsTempFile("OSX (Panther).vssf", "OSX (Panther).vssf", true);
            this.visualStyler1.LoadVisualStyle(skinFile);
        }

        private void toolStripButtonQuery_Click(object sender, EventArgs e)
        {
            new Thread(() => DoQuery()){IsBackground = true}.Start();
        }

        private void DoOutput(string str)
        {
            _outputRows++;
            if (_outputRows > 300)
            {
                this.textBoxOutput.Clear();
                _outputRows = 0;
            }
            this.textBoxOutput.Text = DateTime.Now.ToString() + " " + str + "\r\n" + this.textBoxOutput.Text;
        }

        private void checkBoxSeriesAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < panelSeries.Controls.Count; i++)
            {
                CheckBox cb = panelSeries.Controls[i] as CheckBox;
                cb.Checked = checkBoxSeriesAll.Checked;
            }
        }

        private void toolStripButtonMonitor_Click(object sender, EventArgs e)
        {
            if (!IsLogined())
                return;

            if (this.toolStripButtonMonitor.Tag == null)
            {
                // 获取抢购列表
                List<ProductDetail> neededProductList = new List<ProductDetail>();
                for (int i = 0; i < listBoxCurProductList.Items.Count; i++)
                {
                    var product = listBoxCurProductList.Items[i] as ProductDetail;
                    neededProductList.Add(product);
                }
                if (neededProductList.Count < 1)
                {
                    MsgBox.Warning("请先添加需要抢购的商品！");
                    return;
                }
                // 获取收货地址
                AddressDetail address = this.textBoxCurAddress.Tag as AddressDetail;
                if (address == null)
                {
                    MsgBox.Warning("请先选择收货地址！");
                    return;
                }
                _monitorThread = new Thread(() => DoMonitor(neededProductList, address));
                _monitorThread.IsBackground = true;
                _monitorThread.Start();
                this.toolStripButtonMonitor.Text = "停止抢购";
                this.toolStripButtonMonitor.Tag = "";
            }
            else
            {
                DoOutput("正在停止抢购...");
                this.toolStripButtonMonitor.Enabled = false;
                this.toolStripButtonMonitor.Text = "停止中";
                _isMonitorRunning = false;
            }
        }

        private void DoQuery()
        {
            // 获取查询参数
            List<ProductCategory> categoryList = new List<ProductCategory>();
            for (int i = 0; i < this.panelSeries.Controls.Count; i++)
            {
                CheckBox cb = this.panelSeries.Controls[i] as CheckBox;
                if (cb.Checked && cb.Tag != null)
                {
                    categoryList.Add(cb.Tag as ProductCategory);
                }
            }
            if (categoryList.Count == 0)
            {
                MessageBox.Show("请选择筛选种类！");
                return;
            }

            // 设置控件状态
            this.panel2.Enabled = false;
            this.toolStripButtonQuery.Enabled = false;
            this.toolStripButtonMonitor.Enabled = false;

            DoOutput("正在查询...");
            this.listViewProductList.Items.Clear();

            // 查询接口数据
            var productDic = new Dictionary<ProductCategory, List<ProductDetail>>();
            foreach (var category in categoryList)
            {
                try
                {
                    DoOutput("查询种类：" + category.Name);
                    List<ProductDetail> list = _service.QueryProductDetailList(category);
                    productDic.Add(category, list);
                }
                catch (Exception ex)
                {
                    DoOutput("查询接口失败，" + ex.Message);
                }
            }
            // 渲染数据
            int index = 0;
            foreach (var item in productDic)
            {
                var category = item.Key;
                foreach (var product in item.Value)
                {
                    ListViewItem lv = new ListViewItem(new string[]
                    {
                        (++index).ToString(),
                        category.ToString(),
                        product.product.product_id,
                        product.goods_id,
                        product.name,
                        product.product.saleprice.ToString(),
                        product.buy_count.ToString(),
                        product.stock.ToString(),
                        product.IsCanBuyGoods()?"1":"0"
                    });
                    if (product.IsCanBuyGoods())
                    {
                        lv.BackColor = _onSaleColor;
                    }
                    lv.Tag = product;
                    this.listViewProductList.Items.Add(lv);
                }
            }
            DoOutput("共查询到：" + index + "个！");
            this.panel2.Enabled = true;
            this.toolStripButtonMonitor.Enabled = true;
            this.toolStripButtonQuery.Enabled = true;
        }

        private void DoMonitor(List<ProductDetail> neededProductList, AddressDetail address)
        {
            DoOutput("开始抢购...");
            _isMonitorRunning = true;
            this.toolStripButtonQuery.Enabled = false;
            this.toolStripButtonLoginOrLogout.Enabled = false;
            while (true)
            {
                foreach (var product in neededProductList)
                {
                    try
                    {
                        var curInfo = _service.QueryProductDetail(product.product.product_id);
                        if (curInfo.IsCanBuyGoods())
                        {
                            DoOutput("检测到商品可购：" + product.name);

                            string msg = "亲," + product.name + ",";
                            bool isAutoCreateOrder = this.checkBoxAutoCreateOrder.Checked;
                            if (isAutoCreateOrder)
                            {
                                DoOutput("开始自动下单...");
                                _service.CreateOrder(product.product.product_id, 1, address);
                                DoOutput("下单成功，请在手机上及时支付！");
                                msg += "抢到了!"; ;
                            }
                            else
                            {
                                msg += "有货了!"; ;
                            }

                            try
                            {
                                DoTip(msg);
                            }
                            catch
                            {
                            }
                            _isMonitorRunning = false;
                            break;
                        }
                        else
                        {
                            DoOutput(product.name + "，无货");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("创建订单失败"))
                        {
                            DoOutput(ex.Message);

                            _isMonitorRunning = false;
                            break;
                        }
                        DoOutput("监控商品：" + product.name + "异常，" + ex.Message);
                    }
                }

                if (!_isMonitorRunning)
                    break;
                
                bool customQueryInterval = this.checkBoxCustomQueryInternal.Checked;
                int interval = Convert.ToInt32(this.numericUpDownQueryInternal.Value);
                if (!customQueryInterval)
                {
                    interval = new Random().Next(2500, 3500);
                    this.numericUpDownQueryInternal.Value = interval;
                }
                Thread.Sleep(interval);
            }

            _isMonitorRunning = false;
            this.toolStripButtonQuery.Enabled = true;
            this.toolStripButtonMonitor.Enabled = true;
            this.toolStripButtonLoginOrLogout.Enabled = true;
            this.toolStripButtonMonitor.Text = "开始抢购";
            this.toolStripButtonMonitor.Tag = null;
            DoOutput("已停止抢购！");
        }

        /// <summary>
        /// 抢购提示
        /// </summary>
        /// <param name="msg"></param>
        private void DoTip(string msg)
        {
            //气泡提醒
            ShowBalloonTip(msg);

            //声音提醒
            this.buttonTestPlay.Text = "试听";
            buttonTestPlay_Click(null, null);

            //QQ提醒
            WindowInfo wi = this.comboBoxQQWindow.SelectedItem as WindowInfo;
            if (wi != null)
            {
                QQSendKeyMode mode = QQSendKeyMode.CtrlEnter;
                if (this.radioButtonEnter.Checked)
                {
                    mode = QQSendKeyMode.Enter;
                }
                _qqNotify.SendQQMessage(wi.Hwnd, msg, mode);
            }
        }

        /// <summary>
        /// 在系统托盘显示气泡信息
        /// </summary>
        /// <param name="tipText">提示信息</param>
        private void ShowBalloonTip(string tipText)
        {
            this.notifyIcon1.ShowBalloonTip(3000, "提示", tipText, ToolTipIcon.Info);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            string appName = this.Text;
            if (MessageBox.Show("确定要退出" + appName + "？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) !=
                DialogResult.OK)
            {
                e.Cancel = true;
            }
        }

        private void toolStripButtonQueryAddress_Click(object sender, EventArgs e)
        {
            if (!IsLogined())
                return;

            RunTaskThread(()=>{
                this.listViewAddressList.Items.Clear();
                DoOutput("查询收货地址...");
                try
                {
                    var result = _service.QueryAddressList();
                    for (int i = 0; i < result.Count; i++)
                    {
                        var address = result[i];
                        this.listViewAddressList.Items.Add(new ListViewItem(new string[]{
                        (i+1).ToString(),
                        address.addr_id,
                        address.name,
                        address.mobile,
                        address.GetProvince(),
                        address.GetCity(),
                        address.GetCountry(),
                        address.addr
                    }));
                    }
                    DoOutput("查询收货地址成功！");
                }
                catch (Exception ex)
                {
                    DoOutput("查询收货地址失败," + ex.Message);
                }
            });
        }

        private void listViewProductList_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (this.listViewProductList.SelectedItems.Count > 0)
                {
                    ContextMenuStrip cms = new ContextMenuStrip();
                    cms.Items.Add("添加到抢购列表", null, (o, args) => {
                        var selectedItems = this.listViewProductList.SelectedItems;
                        for (int i = 0; i < selectedItems.Count; i++)
                        {
                            var selectedItem = selectedItems[i];
                            var product = selectedItem.Tag as ProductDetail;
                            bool isAdded = false;
                            for (int j = 0; j < this.listBoxCurProductList.Items.Count; j++)
                            {
                                var p = this.listBoxCurProductList.Items[j] as ProductDetail;
                                if (p.goods_id == product.goods_id)
                                {
                                    isAdded = true;
                                    break;
                                }
                            }
                            if (!isAdded)
                            {
                                this.listBoxCurProductList.Items.Add(product);
                            }
                        }
                    });
                    cms.Items.Add("查看商品图片", null, (o, args) => {
                        var selectedItems = this.listViewProductList.SelectedItems;
                        var selectedItem = selectedItems[0];
                        var product = selectedItem.Tag as ProductDetail;
                        if (product.images.Count > 0)
                        {
                            string imgUrl = product.images[0].url;
                            Image img = _service.DownloadImage(imgUrl);
                            var frm = new FrmViewPic(img);
                            frm.ShowDialog();
                        }
                    });
                    cms.Items.Add("查看商品详情", null, (o, rags) => { 
                        var selectedItems = this.listViewProductList.SelectedItems;
                        var selectedItem = selectedItems[0];
                        var product = selectedItem.Tag as ProductDetail;
                        var url = _service.GetProductDetailUrl(product.product.product_id);
                        Process.Start(url);
                    });
                    cms.Show(this.listViewProductList, e.Location);
                }
            }
        }

        private void listBoxCurProductList_MouseUp(object sender, MouseEventArgs e)
        {
            if (_isMonitorRunning)
                return;

            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (this.listBoxCurProductList.Items.Count > 0)
                {
                    ContextMenuStrip cms = new ContextMenuStrip();
                    cms.Items.Add("从抢购列表中移除", null, (o, args) =>
                    {
                        var items = this.listBoxCurProductList.SelectedItems;
                        for (int i = 0; i < items.Count; i++)
                        {
                            var item = items[i];
                            this.listBoxCurProductList.Items.Remove(item);
                        }
                    });
                    cms.Show(this.listBoxCurProductList, e.Location);
                }
            }
        }

        private void buttonSelectAddress_Click(object sender, EventArgs e)
        {
            if (!IsLogined())
                return;

            var frm = new FrmSelectAddress(_service);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBoxCurAddress.Tag = frm.SelectedAddress;
                this.textBoxCurAddress.Text = frm.SelectedAddress.ToString();
            }
        }

        private void toolStripButtonLoginOrLogout_Click(object sender, EventArgs e)
        {
            var frm = new FrmLogin(_service);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    var userInfo = _service.QueryUserInfo();
                    if (userInfo == null)
                    {
                        throw new Exception("未登陆");
                    }
                    DoOutput("登陆成功：" + userInfo.Mobile);
                    this.toolStripStatusLabel1.Text = "用户：" + userInfo.Mobile;
                    this.toolStripStatusLabel1.Tag = userInfo;
                    string cookie = _service.GetCookie();
                    ConfigStorate.SaveUser(userInfo.Mobile, cookie);
                }
                catch (Exception ex)
                {
                    DoOutput("登录失败," + ex.Message);
                    this.toolStripStatusLabel1.Text = "用户";
                    this.toolStripStatusLabel1.Tag = null;
                }
            }
        }

        private bool IsLogined()
        {
            bool logined = this.toolStripStatusLabel1.Tag != null;
            if (!logined)
            {
                MsgBox.Warning("请先登录！");
            }
            return logined;
        }

        private void checkBoxCustomQueryInternal_CheckedChanged(object sender, EventArgs e)
        {
            this.numericUpDownQueryInternal.Enabled = this.checkBoxCustomQueryInternal.Checked;
        }

        private void buttonGetQQWindow_Click(object sender, EventArgs e)
        {
            this.comboBoxQQWindow.Items.Clear();
            _qqNotify.FillQQWindowList((wi) => {
                this.comboBoxQQWindow.Items.Add(wi);
            });
        }

        private void buttonTestPlay_Click(object sender, EventArgs e)
        {
            if (this.buttonTestPlay.Text == "试听")
            {
                this.buttonTestPlay.Text = "停止";
                if (this.comboBoxMusicList.SelectedItem != null)
                {
                    string filename = this.comboBoxMusicList.SelectedItem.ToString();
                    string file = Application.StartupPath + "\\audio\\" + filename;
                    _musicPlayer.Play(file);
                }
            }
            else
            {
                this.buttonTestPlay.Text = "试听";
                _musicPlayer.Stop();
            }
        }

        private void buttonTestSendQQMsg_Click(object sender, EventArgs e)
        {
            if (this.comboBoxQQWindow.SelectedItem == null)
            {
                return;
            }

            WindowInfo wi = this.comboBoxQQWindow.SelectedItem as WindowInfo;
            QQSendKeyMode mode = QQSendKeyMode.CtrlEnter;
            if (this.radioButtonEnter.Checked)
            {
                mode = QQSendKeyMode.Enter;
            }
            _qqNotify.SendQQMessage(wi.Hwnd, "测试", mode);
        }

        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Icon = this.Icon;
                this.notifyIcon1.Text = this.Text;
                this.notifyIcon1.Visible = true;
                ShowBalloonTip("我在这里！");
            }
        }
    }
}
